package cn.com.bluemoon.daps.sync.base;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.StringJoiner;
import java.util.stream.Collectors;

/**
 * @author Jarod.Kong
 * @date 2021-06-05 14:01
 **/
@Builder
@Data
@AllArgsConstructor
@NoArgsConstructor
public class BmScript {
    public static final String SQL_SPLIT_CHAR = "\u0007\n";
    public static final String SQL_SPLIT_CHAR_RL = "\u0007";
    public static final String PT_SQL_SPLIT_CHAR = ",";
    /**
     * 标准sql
     */
    private String sql;
    /**
     * 标准sql s
     */
    private List<String> sqls;
    /**
     * pt sql
     */
    private String ptSql;
    /**
     * pt sql
     */
    private List<String> ptSqls;
    /**
     * 全量、整合的脚本（针对标准sql+ptsql对应的ddl进行合并，最全的脚本
     * 目前用在申请发布中对比后的结果数据入库到表dap_sync_prod_env_task_detail#ddl字段中
     * 发布同步拿dap_sync_prod_env_task_detail#ddl字段放入到该字段上才存在改脚本数据
     */
    private String fullSql;

    public static BmScript empty() {
        return new BmScript();
    }

    @Override
    public String toString() {
        return new StringJoiner(", ", BmScript.class.getSimpleName() + "[", "]")
                .add("sqls=" + getSqls())
                .add("ptSqls=" + getPtSqls())
                .add("fullSql=" + getFullSqls())
                .toString();
    }

    public String getSql() {
        if (this.sqls != null && !this.sqls.isEmpty()) {
            return String.join(SQL_SPLIT_CHAR, this.sqls);
        }
        return sql;
    }

    public List<String> getFullSqls() {
        if (fullSql == null) {
            return null;
        }
        String[] sql = fullSql.split(SQL_SPLIT_CHAR_RL);
        return Arrays.stream(sql).filter(StringUtils::isNotBlank).collect(Collectors.toList());
    }

    public List<String> getSqls() {
        if (sqls != null && !sqls.isEmpty()) {
            return sqls;
        }
        if (sql != null) {
            return Arrays.stream(sql.split(SQL_SPLIT_CHAR_RL)).collect(Collectors.toList());
        }
        return Collections.emptyList();
    }

    public List<String> getPtSqls() {
        if (ptSqls != null && !ptSqls.isEmpty()) {
            return ptSqls;
        }
        if (ptSql != null) {
            return Arrays.stream(ptSql.split(PT_SQL_SPLIT_CHAR)).collect(Collectors.toList());
        }
        return Collections.emptyList();
    }

    public String getPtSql() {
        if (this.ptSqls != null && !this.ptSqls.isEmpty()) {
            return String.join(PT_SQL_SPLIT_CHAR, this.ptSqls);
        }
        return ptSql;
    }
}
